let slideIndex = 0;
let timeoutId;
const slides = document.querySelectorAll('.slide2');
const duration = 3000; // 每张图片显示的持续时间，单位毫秒

function fadeOutAllBut(index) {
  slides.forEach((slide, idx) => {
    slide.style.opacity = idx === index ? 1 : 0;
  });
}

function startCarousel() {
  timeoutId = setTimeout(() => {
    slideIndex = (slideIndex + 1) % slides.length;
    fadeOutAllBut(slideIndex);
    startCarousel();
  }, duration);
}

const prevButton = document.querySelector('.prev');
const nextButton = document.querySelector('.next');

prevButton.addEventListener('click', () => {
  clearTimeout(timeoutId); // 清除定时器
  slideIndex = (slideIndex - 1 + slides.length) % slides.length;
  fadeOutAllBut(slideIndex);
  setTimeout(startCarousel, duration);
});

nextButton.addEventListener('click', () => {
  clearTimeout(timeoutId); // 清除定时器
  slideIndex = (slideIndex + 1) % slides.length;
  fadeOutAllBut(slideIndex);
  setTimeout(startCarousel, duration);
});

// 初始化
fadeOutAllBut(slideIndex);
startCarousel();